--require "MainScene"
JLSLLayer={}
JLSLLayerFunc={}
JLSLLayerFunc.__index = JLSLLayerFunc
setmetatable(JLSLLayer, JLSLLayerFunc)
JLSLLayer.refreshCD = {[1]=0, [2]=0, [3]=0} 
--JLSLLayer.refresh2CD = 0
--JLSLLayer.refresh3CD = 0 

JLSLLayer.NodeID = {HeroTable=1001}
local HeroItemID = {ImgBK=2001, TongShuai=2002, ZhanShu=2003, BaoPo=2004, JueZhao=2005, Name=2006, Button=3001}

JLSLLayerFunc.getNode = function()
  local l = {}
  setmetatable(l, JLSLLayerFunc)
  l.node = CCBReader:load("JunXiaoLayer0.ccbi")
  --l.node:registerScriptTouchHandler(onTouchJLSLLayer, false, 0, false)
  --l.node:setTouchEnabled(true)
  JLSLLayer.instance = l
  print("JLSLLayer.getNode", JLSLLayer.instance, JLSLLayer.instance.node)
  l:init() 
  return l 
end

JLSLLayerFunc.getScene = function(self)
  local sc = CCScene:create()
  sc:addChild(JLSLLayer:getNode().node)  
  print("JLSLLayer.getScene", sc)
  return sc
end

JLSLLayerFunc.init = function(self)
  self:initTable()
  setObjectExtTable(self.node:getChildByTag(1020), self)
  setObjectExtTable(self.node:getChildByTag(1021), self)
  setObjectExtTable(self.node:getChildByTag(1022), self)

  print("JLSLLayerFunc.init begin")
  TypeCast(self.node:getChildByTag(1013), "CCLabelTTF"):setString(tostring(UserData.config.models.GeneralRefresh[1].coin))
  TypeCast(self.node:getChildByTag(1014), "CCLabelTTF"):setString(tostring(UserData.config.models.GeneralRefresh[2].coin))
  TypeCast(self.node:getChildByTag(1015), "CCLabelTTF"):setString(tostring(UserData.config.models.GeneralRefresh[3].coin))
  print("JLSLLayerFunc.init edn")
  --[[
  ]]
  --self:checkCooldown()
  self:setTimers()
end
JLSLLayerFunc.setTimers = function(self)
  if self.uitimers~=nil then
    for i=1, 3 do
      if self.uitimers[i]~=nil then
        self.node:removeChild(self.uitimers[i].view, true)
        UITimer.removeUITimer(self.uitimers[i])       
      end
    end
  end
  self.timeLabels = {}
  self.buttons = {}
  self.uitimers = {}
  self.uitimerPos = {ccp(720, 460), ccp(720,390), ccp(720, 320)} 
  for i=1,3 do
    self.timeLabels[i] = TypeCast(self.node:getChildByTag(1010+i-1), "CCLabelTTF")
    self.buttons[i] = TypeCast(self.node:getChildByTag(1020+i-1), "CCButton")
    local cd = UserData.userinfo.host.store.refresh[string.format("cd%d", i)] - TimeManager.getServerTime()
    if cd>0 then
      self.uitimers[i] = UITimer.createUITimer(string.format("refreshgeneralcd%d", i), cd, self, ccp(-190,15), ccp(0, 0))
      self.uitimers[i].button:setTitle("立即刷新")
      self.uitimers[i].button:setBackgroundImg("btn_yellow_normal.png", "btn_yellow_highlight.png", "btn_disabled.png")
      --self.uitimers[i].button:setBackgroundImg("btn_blue_normal.png", "btn_blue_highlight.png", "btn_disabled.png")
      self.uitimers[i].view:setPosition(self.uitimerPos[i])
      self.node:addChild(self.uitimers[i].view)
      self.timeLabels[i]:setVisible(false)
      self.buttons[i]:setVisible(false)
      self.buttons[i]:setEnabled(false)
    end
  end
end
JLSLLayerFunc.initTable = function(self)
  if self.table~=nil then
    self.node:removeChild(self.table, true)
  end
  self.shouluButtons = {}
  local heros = UserData.userinfo.host.store.refresh.g
  local items = CCArray:create()
  for k,v in pairs(heros) do
    print("initArmygroupTable", k, v)
    local item = CCBReader:load("JiangLingItem.ccbi")
    local info = UserData.config.models.General[v]
    local skillName = UserData.config.models.NewSkill[info.skill].name
   
    local imgName = string.format("%s_100.png",info.asset)
    --function addButtonFromBK(node, bkid, imgName, title, action, target)
    local b = addButtonFromBK(item, HeroItemID.ImgBK, imgName, "", "onClickHero", self)
    b:setTag(tonumber(v)) 
    --local imgBK = item:getChildByTag(HeroItemID.ImgBK)
    --local sp = CCSprite:create(imgName)
    --sp:setPosition(imgBK:getPosition())
    --item:addChild(sp)

    local lb = item:getChildByTag(HeroItemID.Name) 
    TypeCast(lb, "CCLabelTTF"):setString(info.name)
    
    lb:setColor(Equip.EquipColor[info.quality])
 
    lb = item:getChildByTag(HeroItemID.TongShuai)
    TypeCast(lb, "CCLabelTTF"):setString(tostring(info.initCommander))
    lb = item:getChildByTag(HeroItemID.ZhanShu)
    TypeCast(lb, "CCLabelTTF"):setString(tostring(info.initTactics))
    lb = item:getChildByTag(HeroItemID.BaoPo)
    TypeCast(lb, "CCLabelTTF"):setString(tostring(info.initBlast))
    lb = item:getChildByTag(HeroItemID.JueZhao)
    TypeCast(lb, "CCLabelTTF"):setString(skillName)
    
    local b = item:getChildByTag(HeroItemID.Button)
    setObjectExtTable(b, self)
    b:setTag(k)
    self.shouluButtons[#self.shouluButtons+1] = b

    item:setContentSize(CCSizeMake(320,190)) 
    items:addObject(item)
  end
  if items:count()==0 then return;end
  --self.items = items
  local tableBK = self.node:getChildByTag(JLSLLayer.NodeID.HeroTable)
  local size = tableBK:getContentSize() 
  local tableview = CCTableView:create(0, CCSizeMake(size.width-20, size.height), items)
  local x, y = ActionUtil.leftBottomPoint(tableBK)
  tableview:setPosition(x+10, y+15)
  self.node:addChild(tableview)
  self.table = tableview
end
JLSLLayerFunc.onShouLuButton = function(self, node, event)
  print("JLSLLayerFunc.onShouLuButton", node:getTag())
  local heros = UserData.userinfo.host.store.refresh.g
  self.currentHeroIndex = node:getTag()
  NetworkRequest.shouluGeneral(heros[node:getTag()], "onShouLuComplete", self) 
  --setTouchEnabledAll(JunXiaoScene.instance.node, false)
  LoadScene:showLoadingScene()
end
JLSLLayerFunc.onShouLuComplete = function(self, data)
  LoadScene:removeLoadingScene()
  --setTouchEnabledAll(JunXiaoScene.instance.node, true)
  local res = cjson.decode(data)
  if res.ret==0 then
    NetworkRequest.syncData(res)
    local heros = UserData.userinfo.host.store.refresh.g
    heros[self.currentHeroIndex] = nil
    self:initTable()
    if JunXiaoScene.guide1==true then
      JunXiaoGuide.nextStep()
    end
  else
    showMessage(res.msg, ccc3(255,255,0))
  end
end
JLSLLayerFunc.onClickHero= function(self, node, event)
  print("JLSLLayerFunc.onHeroButton touched ", event, node:getTag())
  if self.curTip~=nil then
    self.node:removeChild(self.curTip, true)
  end
  local hd = HeroData:create(node:getTag())
  local tip = hd:createTip()
  self.curTip = tip
  self.node:addChild(self.curTip)
  self.curTip:registerScriptTouchHandler(JLSLLayerFunc.onTouchTipLayer, false, -1111, true)
  self.curTip:setTouchEnabled(true)
end
JLSLLayerFunc.onTouchTipLayer = function(event, x, y)
  if event==CCTOUCHBEGAN then
    if JLSLLayer.instance.curTip~=nil then
      print("onTouchTipLayer clear tip")
      JLSLLayer.instance.node:removeChild(JLSLLayer.instance.curTip, true)
      JLSLLayer.instance.curTip = nil
    end
  end
  return true 
end
--[[
JLSLLayerFunc.checkCooldown = function(self)
  if JLSLLayer.refreshCD[1]>0 or JLSLLayer.refreshCD[2]>0 or JLSLLayer.refreshCD[3]>0 then
    if JLSLLayer.assignTimerID==nil then
      JLSLLayer.assignTimerID = CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(JLSLLayerFunc.onRefreshTimer, 1, false)
    end 
  end
  JLSLLayer.instance:setCoolDownLabel()
end
]]
--[[
JLSLLayerFunc.setCoolDownLabel = function(self)
  for k,v in pairs(JLSLLayer.refreshCD) do
    local lb = self.node:getChildByTag(1010+k-1)
    if JLSLLayer.refreshCD[k]<=0 then
      TypeCast(lb, "CCLabelTTF"):setString("可以刷新")
      TypeCast(self.node:getChildByTag(1020+k-1), "CCButton"):setEnabled(true)
    else
      TypeCast(self.node:getChildByTag(1020+k-1), "CCButton"):setEnabled(false)
      TypeCast(lb, "CCLabelTTF"):setString(formatSecond(JLSLLayer.refreshCD[k]))
    end
  end
end
JLSLLayerFunc.onRefreshTimer = function()
  print("JLSLLayerFunc.onRefreshTimer")
  for k,v in pairs(JLSLLayer.refreshCD) do
    JLSLLayer.refreshCD[k] = JLSLLayer.refreshCD[k]-1
  end
  if JLSLLayer.instance~=nil then
    JLSLLayer.instance:setCoolDownLabel()
  end
  if JLSLLayer.refreshCD[1]<=0 and JLSLLayer.refreshCD[2]<=0 and JLSLLayer.refreshCD[3]<=0 then
    CCDirector:sharedDirector():getScheduler():unscheduleScriptEntry(JLSLLayer.assignTimerID)
    JLSLLayer.assignTimerID=nil
  end
end
--]]
JLSLLayerFunc.onRefreshButton = function(self, node, event)
  local index = node:getTag()-1020+1
  NetworkRequest.refreshGeneral(index, "onRefreshComplete",self)
  self.index = index
  --setTouchEnabledAll(JunXiaoScene.instance.node, false)
  LoadScene:showLoadingScene()
  --if JLSLLayer.assignTimerID==nil then
  --  JLSLLayer.assignTimerID = CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(JLSLLayerFunc.onRefreshTimer, 1, false)
  --end 
  --TypeCast(self.node:getChildByTag(1020+index-1), "CCButton"):setEnabled(false)
  --self:checkCooldown() 
end
JLSLLayerFunc.onRefreshComplete = function(self, data)
  print("JLSLLayerFunc.onRefreshComplete", data)
  --setTouchEnabledAll(JunXiaoScene.instance.node, true)
  LoadScene:removeLoadingScene()
  local res = cjson.decode(data)
  if res.ret==0 then
    NetworkRequest.syncData(res)
    UserData.userinfo.host.store.refresh.g = res.generals
    self:initTable()
    --TimeManager.saveCDTime("assigncd", info.duration)
    --JLSLLayer.refreshCD[self.curIndex] = 10
    --JLSLLayer.refreshCD[self.index] = UserData.config.models.GeneralRefresh[self.index].cdtime 
    --self:checkCooldown() 
    self:setTimers()
    if JunXiaoScene.guide1==true then
      JunXiaoGuide.nextStep()
    end 
  else
    showMessage(res.msg, ccc3(255,255,0))
    --TypeCast(self.node:getChildByTag(1020+index-1), "CCButton"):setEnabled(true)
  end
end

--处理加速
JLSLLayerFunc.onTimerEnd = function(self, timer)
  if timer~=nil then
    timer.view:getParent():removeChild(timer.view, true)
  end
  for i=1,3 do
    if timer==self.uitimers[i] then
      self.timeLabels[i]:setVisible(true)
      self.buttons[i]:setVisible(true)
      self.buttons[i]:setEnabled(true)
    end
  end
end
JLSLLayerFunc.onJiaSuButton = function(self, timer, pars)
  for i=1,3 do
    UITimer.removeUITimer(self.uitimers[i])
    if timer==self.uitimers[i] then 
      self.jiasuID = i
    end
  end
  local cd = UserData.userinfo.host.store.refresh[string.format("cd%d", self.jiasuID)] - TimeManager.getServerTime()
  local timeCD = UserData.config.models.GeneralRefresh[self.jiasuID].cdtime
  local coin = UserData.config.models.GeneralRefresh[self.jiasuID].coin
  local cost = math.ceil(cd/timeCD*coin)
  local msg = string.format("是否花费%d军饷刷新将领", cost)
  local tmp = Dialog:create("刷新将领", msg, self)
  self.cost = cost
  print("JLSLLayerFunc.onJiaSuConfirm", self.jiasuID, cost, timeCD, cd, coin)
  MainScene.scene:addChild(tmp.node)
  MainScene.scene:removeChild(JunXiaoScene.instance.node, true) 
  self.dlg = tmp 
end
JLSLLayerFunc.onConfirm = function(self, dlg, confirm)
  if confirm==false then
    MainScene.scene:removeChild(dlg.node, true)
    MainScene.scene:addChild(JunXiaoScene.getNode().node)
  else
    NetworkRequest.resetAndRefreshGeneral(self.jiasuID, self.cost, "onJiaSuComplete", self) 
    --setTouchEnabledAll(dlg.node, false)
    LoadScene:showLoadingScene()
  end
end

JLSLLayerFunc.onJiaSuComplete = function(self, data)
  print("JLSLLayerFunc.onJiaSuComplete", data)
  LoadScene:removeLoadingScene()
  local res = cjson.decode(data)
  if res.ret==0 then
    NetworkRequest.syncData(res)
    if self.dlg~=nil then
      self.uitimers[self.jiasuID]:endTimer()
    end
  else
    showMessage(res.msg, ccc3(255,255,0))
  end

  if self.dlg~=nil then
    MainScene.scene:removeChild(self.dlg.node, true)
  end
  MainScene.scene:addChild(JunXiaoScene.getNode().node)
end
JLSLLayerFunc.clearUITimers = function(self)
  for i=1,3 do
    UITimer.removeUITimer(self.uitimers[i])
  end  
end
